var express = require('express');
var router = express.Router();
const jwt = require('jsonwebtoken');
const jwtConfig = require('../config/index').jwt;
const axios = require('axios');
const LoginModel = require('../model/login');
const userRoutes = require('./user');
const flowerRoutes = require('./flower');
const gardenRoutes = require('./garden');
const gameRoutes = require('./game');

/* GET home page. */
router.get('/', function (req, res, next) {
  res.send({
    code: 200,
    msg: "ok"
  });
});

// 将用户路由挂载到 '/users' 路径下
router.use('/users', userRoutes);
// 将花盆路由挂载到 '/flower' 路径下
router.use('/flower', flowerRoutes);
// 将花园路由挂载到 '/garden' 路径下
router.use('/garden', gardenRoutes);
// 将游戏路由挂载到 '/game' 路径下
router.use('/game', gameRoutes);

// 通过 StaticID 获取 StaticURL
router.get('/GetStaticURL', async (req, res, next) => {
  const StaticID = req.query.StaticID;
  const token = req.headers.authorization.split(' ')[1]; // 去除 "Bearer " 后的 token
  console.log('收到的Token:',token);
  if (!token) {
    return res.status(401).send({
      code: 401,
      msg: '未授权访问，缺少 token'
    });
  }
  try {
      const StaticURL = await LoginModel.getStatic(StaticID);
      res.status(200).send({
          code: 200,
          msg: "成功获取数据链接",
          data: StaticURL
      });
  } catch (error) {
      res.status(500).send({
          code: 500,
          msg: `获取数据链接失败: ${error.message}`
      });
  }
});


router.get('/login', function (req, res, next) {
  let appid = 'wxb4672b59254ae7f0';
  let secret = '17c524dc3667e20a90015a6d1886e73c';
  let js_code = req.query.code;
  let grant_type = 'authorization_code';

  let queryString = `appid=${appid}&secret=${secret}&js_code=${js_code}&grant_type=${grant_type}`;
  axios.get('https://api.weixin.qq.com/sns/jscode2session?' + queryString)
    .then(response => {
      console.log('请求腾讯API成功', response.data);

      // 从响应中提取openid和session_key
      const openid = response.data.openid;
      // const session_key = response.data.session_key;

      // 模拟从API获取的用户昵称和头像（测试用）
      const nickname = "请输入昵称";
      const avatarUrl = "http://localhost:3000/images/Haed.png";

      // 查询数据库中是否存在该用户
      LoginModel.findUserByOpenid(openid)
        .then(user => {
          if (user) {
            // 如果用户存在，更新最后登录时间
            return LoginModel.updateLastLoginTime(openid)
              .then(() => {
                // 生成JWT token
                const token = jwt.sign({ openid: openid }, jwtConfig.jwtSecret, {
                  expiresIn: jwtConfig.jwtExpiresIn,
                  algorithm: jwtConfig.algorithm[0]
                });

                res.status(200).send({
                  code: 200,
                  msg: "ok",
                  data: {
                    token: `Bearer ${token}`
                  }
                });
              });
          } else {
            // 如果用户不存在，添加用户信息到数据库
            return LoginModel.addOpenidAndUserInfo(openid, nickname, avatarUrl)
              .then(() => {
                // 生成JWT token
                const token = jwt.sign({ openid: openid }, jwtConfig.jwtSecret, {
                  expiresIn: jwtConfig.jwtExpiresIn,
                  algorithm: jwtConfig.algorithm[0]
                });

                res.status(200).send({
                  code: 200,
                  msg: "ok",
                  data: {
                    token: `Bearer ${token}`
                  }
                });
              });
          }
        })
        .catch(error => {
          console.error('查询用户信息失败', error);
          res.status(500).send({
            code: 500,
            msg: "查询用户信息失败"
          });
        });

    })
    .catch(error => {
      console.error('请求腾讯API失败', error);
      res.status(500).send({
        code: 500,
        msg: "请求腾讯API失败"
      });
    });
});
module.exports = router;
